package com.cityfood.controller;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
 
import com.cityfood.common.pojo.CityFoodResult;
 
/**
 * 图片上传
 * @date 2017年9月30日下午3:37:00
 * @version 1.0
 */
@Controller
public class UploadController {
	public static final Logger logger = LoggerFactory.getLogger(UploadController.class);
	
	@RequestMapping(value = "/upload", method=RequestMethod.POST)
	@ResponseBody
	public CityFoodResult headImgUpload(HttpServletRequest request, MultipartFile file) {
		CityFoodResult result = new CityFoodResult();
		//Map<String, Object> value = new HashMap<String, Object>();
		try {
			String url = this.updateHead(file);
			logger.debug("图片路径{}",url);
			result.setCode(200);
			result.setData(url);
			result.setMsg("图片上传成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setData(false);
			result.setMsg("图片上传失败");
		}
		return result;
	}
	
	@RequestMapping(value = "/test",method=RequestMethod.GET)
	public String test(Model model){
		model.addAttribute("hello", "你好");
		return "upload";
	}
	
	
	private String updateHead(MultipartFile file) throws IOException {
	    if (file == null || file.getSize() <= 0) {
		      throw new IOException("file不能为空");
		    }
	        OSSClientUtil ossClient=new OSSClientUtil();
		    String name = ossClient.uploadImg2Oss(file);
		    String imgUrl = ossClient.getImgUrl(name);
		    String[] split = imgUrl.split("\\?");
		    return split[0];
	}
	
}
